<template>
  <div class="SignUpDetails">
    <!-- 标题栏 -->
    <mt-header fixed :title="title">
      <mt-button icon="back" slot="left" v-on:click="goBack"></mt-button>
      <mt-button icon="more" slot="right"></mt-button>
    </mt-header>
    <!-- banner -->
    <div
      class="banner"
      :style="{ backgroundImage: 'url(' + master_map + ')' }"
    ></div>
    <!-- 标题 -->
    <p>{{ title }}</p>
    <!-- 标签 -->
    <div class="label">
      <!-- 报名状态 -->
      <span class="labelIfSignUp">{{ IfSignUp }}</span>
      <!-- 分割线 -->
      <span class="labelDividingLine">|</span>
      <!-- 报名人数进度 -->
      <span class="labelProgress">{{ nowProgress }}/{{ allProgress }}</span>
    </div>

    <!-- 灰色分割綫 -->
    <div
      class="greyDividingLine"
      style="width: 100%; height: 0.1875rem; background-color: #F2F2F2; margin-top: 0.625rem;"
    ></div>

    <!-- 标签2 -->
    <div class="label2">
      <div class="labelLocalIcon"></div>
      <span class="labelLocal">{{ local }}</span>
    </div>
    <div class="label2">
      <div class="labelTimeIcon"></div>
      <span class="labelTime">报名截止：{{ time }}</span>
    </div>
    <!-- 灰色分割綫 -->
    <div
      class="greyDividingLine"
      style="width: 100%; height: 0.1875rem; background-color: #F2F2F2; margin-top: 0.625rem;"
    ></div>

    <!-- 详情标签 -->
    <mt-navbar v-model="selected">
      <mt-tab-item id="details">课程详情</mt-tab-item>
      <mt-tab-item id="instantaneous">精彩瞬间</mt-tab-item>
    </mt-navbar>

    <!-- 内容容器 -->
    <mt-tab-container v-model="selected" class="detailsLayout">
      <!-- 课程详情 -->
      <mt-tab-container-item id="details">
        <div class="detailsHTML" v-html="detailsHTML"></div>
      </mt-tab-container-item>
      <!-- 精彩瞬间 -->
      <mt-tab-container-item id="instantaneous">
        222
      </mt-tab-container-item>
    </mt-tab-container>

    <div style="height: 3.5rem;"></div>

    <!-- 底部按钮,注意，因为按钮可能有数量变化，所以用了flex的有空位自动放大。在这里定义按钮宽度是指按钮存在的情况下 -->
    <div class="SignUpButton">
      <mt-button
        type="primary"
        @click="applyStudent(0, money)"
        style="width: 40%; background-color: #FEA5A5;"
        v-if="is_type == 1 ? true : false"
        >{{ money }}元 | 报名试听</mt-button
      >
      <mt-button
        type="primary"
        @click="applyStudent(1, payMoney)"
        style="width: 60%; background-color: #FF0000;"
        >{{ payMoney }}元 | 立即报名</mt-button
      >
    </div>

    <div class="dialog">
      <!--外层的遮罩 点击事件用来关闭弹窗，isShow控制弹窗显示 隐藏的props-->
      <div class="dialog-cover back" v-show="isShow" @click="closeMyself"></div>
      <transition name="drop">
        <div class="dialog-content" v-show="isShow">
          <div class="dialog-top">
            <div class="dialog-colse" @click="closeDialog"></div>
            <div class="dialog-title">填写地址</div>
            <div class="dialog-clear" @click="closeInfo">清除</div>
          </div>
          <!--弹窗的内容-->
          <div class="dialog-con-style">
            <div class="con-style-box">
              <span>姓名</span
              ><input ref="dropName" type="text" :value="address.name" />
            </div>
            <div class="con-style-box">
              <span>电话</span
              ><input
                ref="dropTel"
                type="number"
                placeholder="填写手机号"
                :value="address.phone"
              />
            </div>
            <div class="con-style-box">
              <span>QQ号</span
              ><input ref="dropQQ" type="number" :value="address.qq" />
            </div>
            <div class="con-style-box">
              <span>苑/楼</span
              ><input ref="dropSite1" type="text" :value="address.site1" />
            </div>
            <div class="con-style-box">
              <span>栋数</span
              ><input ref="dropSite2" type="number" :value="address.site2" />
            </div>
            <div class="con-style-box">
              <span>寝室号</span
              ><input
                ref="dropSite3"
                type="text"
                placeholder="4单元 502"
                :value="address.site3"
              />
            </div>
          </div>
          <!--弹窗确认按钮-->
          <div class="dialog-confirm" @click="bounced">确认地址</div>
        </div>
      </transition>
    </div>
  </div>
</template>
<script
  type="text/javascript"
  src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"
></script>
<script>
import { Indicator } from "mint-ui";
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      id: "1",
      orderId: "", //报名订单id
      orderMoney: "",
      code: "",
      url: "",
      money: 10,
      payMoney: 3600,
      is_type: 0, //类型
      master_map: "",
      title: "2020年第12期日语进阶教学",
      IfSignUp: "未报名",
      nowProgress: 2,
      allProgress: 50,
      local: "在线教学",
      time: "2020年8月18日",
      selected: "details",
      detailsHTML:
        '<p><img src="https://jpanese-project.oss-cn-chengdu.aliyuncs.com/public/item_img2.png" alt=""/></p><p style="text-indent:2em;">我是我是简介我是简介我是简介我是简我是简介我是简介我是简介我是简介我是简介我是简介我是简介我是简介介我是简介我是简介我是简介我是简介我是简介我是简介我是简介简介我是简介我是简介我是简介我是简介我是简介我是简介我是简介我是简介我是简介我是简介我是简介</p>',
      status: "", //报名状态 1未填写资料 2 不可以报名 3可以报名
      isShow: false,
      address: []
    };
  },
  created() {
    this.id = localStorage.sign_id;
    this.selectSignUpDetails();
    let me = this;
    if (location.href.indexOf("code=") === -1) {
    } else {
      setTimeout(function() {
        me.wxpay();
      }, 1000);
    }
  },
  methods: {
    //到报名资料卡
    goFromView(id) {
      localStorage.sign_orderId = id;
      this.$router.push({
        name: "SignUpFrom"
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    bounced() {
      //联系地址填写
      let name = this.$refs.dropName.value;
      let tel = this.$refs.dropTel.value;
      let qq = this.$refs.dropQQ.value;
      let site1 = this.$refs.dropSite1.value;
      let site2 = this.$refs.dropSite2.value;
      let site3 = this.$refs.dropSite3.value;
      let siteLess = site1 + "-" + site2 + "-" + site3;

      this.listenStudentInfo(name, tel, qq, siteLess);
    },
    closeMyself() {
      this.isShow = true; //显示弹框
      this.selectBouncedAddress();
    },
    closeDialog() {
      this.isShow = false; //关闭弹窗
    },
    closeInfo() {
      this.address = []; //清除内容
    },
    //弹框获取上一次地址
    selectBouncedAddress() {
      let me = this;
      this.$axios
        .post(
          "/api/apply/bouncedAddress",
          { uid: localStorage.uid },
          { emulateJSON: true }
        )
        .then(kun => {
          //console.log(kun);
          if (kun.code == 200) {
            me.address = kun.data;
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //报名详情页
    selectSignUpDetails() {
      //Indicator.open({ spinnerType: "fading-circle" });
      let me = this;
      this.$axios
        .post(
          "/api/apply/apply_train_details",
          {
            aid: this.id,
            uid: localStorage.uid
          },
          { emulateJSON: true }
        )
        .then(kun => {
          console.log(kun);
          //Indicator.close();
          if (kun.code == 200) {
            (me.title = kun.data.title),
              (me.IfSignUp = kun.data.status),
              (me.nowProgress = kun.data.is_num),
              (me.allProgress = kun.data.nums),
              (me.local = kun.data.addr),
              (me.time = kun.data.stop_time),
              (me.detailsHTML = kun.data.details),
              (me.master_map = kun.data.master_map),
              (me.payMoney = kun.data.money),
              (me.is_type = kun.data.type),
              (me.status = kun.data.sign_up);
          } else {
            Toast(kun.msg);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //报名提交
    applyStudent(val, mon) {
      /* if (this.is_type == 1) {
        if (this.status == 2) {
          Toast(this.IfSignUp);
          return false;
        }
      } */

      //Indicator.open({ spinnerType: "fading-circle" });
      let me = this;
      this.$axios
        .post(
          "/api/apply/apply_student",
          {
            bm_id: this.id,
            uid: localStorage.uid,
            money: mon,
            type: val,
            type_class: this.is_type
          },
          { emulateJSON: true }
        )
        .then(kun => {
          console.log(kun);
          //Indicator.close();
          if (kun.code == 200) {
            if (val == 1) {
              //正式报名--到资料卡
              me.goFromView(kun.data.id);
            } else {
              sessionStorage.setItem("orderId", kun.data.id);
              sessionStorage.setItem("orderMoney", kun.data.money);
              me.isShow = true;
            }
          } else {
            Toast(kun.msg);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    // 截取code
    GetUrlParame(parameName) {
      /// 获取地址栏指定参数的值
      /// <param name="parameName">参数名</param>
      // 获取url中跟在问号后面的部分
      var parames = window.location.search;
      // 检测参数是否存在
      if (parames.indexOf(parameName) > -1) {
        var parameValue = "";
        parameValue = parames.substring(
          parames.indexOf(parameName),
          parames.length
        );
        // 检测后面是否还有参数
        if (parameValue.indexOf("&") > -1) {
          // 去除后面多余的参数, 得到最终 parameName=parameValue 形式的值
          parameValue = parameValue.substring(0, parameValue.indexOf("&"));
          // 去掉参数名, 得到最终纯值字符串
          parameValue = parameValue.replace(parameName + "=", "");
          return parameValue;
        }
        return "";
      }
    },
    wxpay() {
      //微信支付 获取code
      var href = location.href;
      if (href.indexOf("code=") === -1) {
        //如果没有code参数就直接调用授权函数
        this.get_weixin_code_login(); //调用授权函数
      } else {
        //如果有拿取code值
        this.getUrlCode();
        var local = window.location.href;
        console.log(local);
        this.code = this.GetUrlParame("code");
        if (this.code == null || this.code == "" || this.code == "undefined") {
          window.location.href = this.url;
        }
        this.getWxUserInfo(this.code);
      }
    },
    get_weixin_code_login() {
      var uri = window.location.href;
      var appid = "wx3de25cb8ef21fe75"; //自己公众号的appid
      var url =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        appid +
        "&redirect_uri=" +
        encodeURIComponent(uri) +
        "&response_type=code&scope=snsapi_userinfo&state=54321#wechat_redirect";
      window.location.href = url;
      this.url = url;
      // 这里走完就是已经授权了。如果授权了就会url中带有code
    },
    getUrlCode() {
      //获取url参数
      var url = location.search;
      this.winUrl = url;
      var theRequest = new Object();
      if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
      }
      return theRequest;
    },
    getWxUserInfo(code) {
      //授权后获取用户的基本信息
      let me = this;
      console.log("授权码" + code);
      this.$axios
        .post(
          "/api/wxpay/get_sign",
          {
            code: code,
            oid: sessionStorage.getItem("orderId"),
            uid: localStorage.uid,
            money: sessionStorage.getItem("orderMoney")
          },
          { emulateJSON: true }
        )
        .then(kun => {
          console.log("支付参数" + kun);

          if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
              document.addEventListener(
                "WeixinJSBridgeReady",
                me.onBridgeReady,
                false
              );
            } else if (document.attachEvent) {
              document.attachEvent("WeixinJSBridgeReady", me.onBridgeReady);
              document.attachEvent("onWeixinJSBridgeReady", me.onBridgeReady);
            }
          } else {
            //订单创建成功返回支付参数和order_id便于前端唤起支付
            console.log("唤起支付" + kun.appId);
            me.onBridgeReady(
              kun.appId,
              kun.timeStamp,
              kun.nonceStr,
              kun.package,
              kun.paySign,
              kun.signType,
              kun.order_id
            );
          }
        })
        .catch(function(error) {
          alert(error);
        });
    },
    // 支付
    onBridgeReady(
      appid,
      time,
      nonceStr,
      prepay_id,
      paySign,
      trade_type,
      order_id
    ) {
      let me = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: appid, // 公众号名称，由商户传入
          timeStamp: time, // 时间戳，自1970年以来的秒数
          nonceStr: nonceStr, // 随机串
          package: prepay_id, // 统一下单接口返回的prepay_id参数值
          signType: trade_type, // 微信签名方式：
          paySign: paySign // 微信签名
        },
        function(res) {
          console.log(order_id);
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            Toast("支付成功");
            me.listenStudent();
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            Toast("支付过程中用户取消");
          } else if (res.err_msg == "get_brand_wcpay_request:fail") {
            Toast("支付失败");
          } else {
            console.log(res);
          }
        }
      );
    },
    //试听课
    listenStudent() {
      Indicator.open({ spinnerType: "fading-circle" });
      let me = this;
      this.$axios
        .post(
          "/api/apply/listen_student",
          {
            aid: sessionStorage.getItem("orderId"),
            uid: localStorage.uid,
            type: this.is_type
          },
          { emulateJSON: true }
        )
        .then(kun => {
          console.log(kun);
          Indicator.close();
          if (kun.code == 200) {
            me.goMyOrder();
          } else {
            Toast(kun.msg);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //试听课资料
    listenStudentInfo(name, tel, qq, siteLess) {
      this.closeDialog();
      //Indicator.open({ spinnerType: "fading-circle" });
      let me = this;
      this.$axios
        .post(
          "/api/apply/listen_student_info",
          {
            uid: localStorage.uid,
            oid: sessionStorage.getItem("orderId"),
            aid: this.id,
            name: name,
            tel: tel,
            user_qq: qq,
            site: siteLess
          },
          { emulateJSON: true }
        )
        .then(kun => {
          console.log(kun);
          //Indicator.close();
          if (kun.code == 200) {
            me.wxpay();
          } else {
            Toast(kun.msg);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //试听课报名成功后
    goMyOrder() {
      sessionStorage.setItem("orderIndex", "payinfo");
      this.$router.push({
        name: "MyOrder"
      });
    }
  },
  props: {
    //下面这些属性会绑定到div上面 详情参照上面的html结构
    // 如： :style="{top:topDistance+'%',width:widNum+'%'}"
    widNum: {
      //内容宽度
      type: Number,
      default: 60
    },
    leftSite: {
      // 左定位
      type: Number,
      default: 50
    },
    topDistance: {
      //top上边距
      type: Number,
      default: 30
    },
    pdt: {
      //上padding
      type: Number,
      default: 10
    },
    pdb: {
      //下padding
      type: Number,
      default: 11
    }
  }
};
</script>

<style lang="scss" scoped>
p {
  width: 21.5625rem;
  margin: 0rem;
  margin-top: 0.625rem;
  margin-left: 0.9375rem;
  margin-right: 0.9375rem;
  font-size: 0.9375rem;
  color: #333333;
}

// 标题栏
.mint-header {
  height: 2.75rem;
  line-height: 1.25;
  background: rgb(255, 127, 95);
  /* Old browsers */
  background: -moz-linear-gradient(
    -45deg,
    rgb(255, 127, 95) 25%,
    rgb(229, 39, 77) 75%
  );
  /* FF3.6-15 */
  background: -webkit-linear-gradient(
    -45deg,
    rgb(255, 127, 95) 25%,
    rgb(229, 39, 77) 75%
  );
  /* Chrome10-25,Safari5.1-6 */
  background: linear-gradient(
    135deg,
    rgb(255, 127, 95) 25%,
    rgb(229, 39, 77) 75%
  );
  /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff7f5f', endColorstr='#e5274d', GradientType=1);
  /* IE6-9 fallback on horizontal gradient */
}

// banner
.banner {
  width: 100%;
  height: 12.5rem;
  background-image: url(https://jpanese-project.oss-cn-chengdu.aliyuncs.com/public/item_img2.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  overflow: hidden;
}

// 标签
.label {
  margin-top: 0.625rem;
  margin-left: 0.9375rem;
  color: #ff931c;
  font-size: 0.75rem;

  .labelDividingLine {
    margin-left: 0.3125rem;
  }

  .labelProgress {
    margin-left: 0.3125rem;
  }
}

// 标签2

.label2 {
  margin-top: 0.625rem;

  .labelLocalIcon {
    width: 0.625rem;
    height: 0.625rem;
    margin-left: 0.9375rem;
    background-image: url(../assets/local.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    overflow: hidden;
    display: inline-block;
  }

  .labelLocal {
    margin-left: 0.625rem;
    font-size: 0.625rem;
    color: #999999;
  }

  .labelTimeIcon {
    width: 0.625rem;
    height: 0.625rem;
    margin-left: 0.9375rem;
    background-image: url(../assets/time.png);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    overflow: hidden;
    display: inline-block;
  }

  .labelTime {
    margin-left: 0.625rem;
    font-size: 0.625rem;
    color: #999999;
  }
}

//内容标签栏
.mint-navbar {
  width: 8rem;
  margin-left: 0.9375rem;
  font-size: 0.8125rem;
  justify-content: space-between;

  > :last-child {
    margin-left: 0.9375rem;
  }

  .mint-tab-item.is-selected {
    border-bottom: 0.1875rem solid #ff0000;
    color: #ff0000;
  }
}

//内容
.detailsLayout {
  margin-top: 1.25rem;

  //使用了scoped的css无法用普通方法修改动态插入的HTML，所以用这个方法来穿透，穿透原理未知
  /deep/ p {
    margin: 0rem;

    // 保障动态传入的富文本编辑器的HTML的图片能够适配手机
    img {
      width: 100%;
      -ms-interpolation-mode: bicubic;
    }
  }
}

// 底部按钮，按钮可能有数量变化，所以就不在这里制定按钮宽度，直接采用flex的有空位自动放大，在HTML里面设置默认宽度，而不是在css，这样可以省写两个class去单独配置按钮宽度
.SignUpButton {
  display: flex;
  position: fixed;
  bottom: 0rem;
  width: 100%;
  height: 3.0625rem;

  // 按钮公共样式
  .mint-button {
    height: 3.0625rem;
    border-radius: 0rem;
    flex-grow: 1;
    font-size: 0.9375rem;
    padding: 0rem;
  }
}

//弹框
// 最外层 设置position定位
.dialog {
  position: relative;
  color: #2e2c2d;
}
// 遮罩 设置背景层，z-index值要足够大确保能覆盖，高度 宽度设置满 做到全屏遮罩
.dialog-cover {
  background: rgba(0, 0, 0, 0.8);
  position: fixed;
  z-index: 9999;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
// 内容层 z-index要比遮罩大，否则会被遮盖，
.dialog-content {
  position: fixed;
  bottom: 0;
  // 移动端使用felx布局
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
//弹框内容
.dialog-content {
  width: 100%;
  height: 26.25rem;
  border-radius: 1.875rem 1.875rem 0 0;
  background-color: white;

  //顶部
  .dialog-top {
    border-bottom: 0.0625rem solid #e6e6e6;
    width: 100%;
    height: 2.9375rem;
    position: absolute;
    top: 0;

    div {
      display: inline-block;
      line-height: 2.9375rem;
      position: absolute;
    }
    .dialog-colse {
      width: 0.8125rem;
      height: 0.8125rem;
      top: 1.21875rem;
      left: 0.90625rem;
      background-image: url(../assets/shop/clear.png);
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center;
      overflow: hidden;
    }
    .dialog-title {
      font-size: 1.125rem;
      color: #343434;
      font-family: PingFang SC;
      font-weight: 500;

      left: 50%;
      -ms-transform: translateX(-50%) translateY(0); /* IE 9 */
      -moz-transform: translateX(-50%) translateY(0); /* Firefox */
      -webkit-transform: translateX(-50%) translateY(0); /* Safari 和 Chrome */
      -o-transform: translateX(-50%) translateY(0); /* Opera */
    }
    .dialog-clear {
      right: 0.9375rem;
      font-size: 0.75rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #ffffff;
      background: linear-gradient(-10deg, #ff8060 0%, #e5284e 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }
  //内容
  .dialog-con-style {
    width: 18.75rem;
    position: absolute;
    top: 3.875rem;

    .con-style-box {
      margin-bottom: 0.625rem;
      height: 1.875rem;
      position: relative;

      span {
        height: 100%;
        display: inline-block;
        width: 5.25rem;
        font-size: 0.9375rem;
        font-family: PingFang SC;
        font-weight: 400;
        color: #343434;
        line-height: 1.875rem;
        text-align: right;
      }
      input {
        outline: none;
        width: 10.9375rem;
        height: 100%;
        border: 0.03125rem solid #dedddd;
        border-radius: 0.3125rem;
        position: absolute;
        right: 1.1875rem;
      }
    }
  }

  //确认按钮
  .dialog-confirm {
    width: 18.75rem;
    height: 3.125rem;
    position: absolute;
    top: 20rem;
    border-radius: 1.5625rem;
    line-height: 3.125rem;
    text-align: center;
    font-size: 1.125rem;
    font-family: PingFang SC;
    font-weight: 500;
    color: #ffffff;

    /* 设置渐变 */
    background: rgb(255, 0, 0); /* Old browsers */
    background: -moz-linear-gradient(
      to right bottom,
      rgb(255, 127, 95) 10%,
      rgb(229, 39, 77) 70%
    ); /* FF3.6-15 */
    background: -webkit-linear-gradient(
      to right bottom,
      rgb(255, 127, 95) 10%,
      rgb(229, 39, 77) 70%
    ); /* Chrome10-25,Safari5.1-6 */
    background: linear-gradient(
      to right bottom,
      rgb(255, 127, 95) 30%,
      rgb(229, 39, 77) 80%
    ); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ff0000', endColorstr='#ffffff',GradientType=0 ); /* IE6-9 */
  }
}
</style>
